package net.sf.midollo.net.cgitunnel.client;

import net.sf.midollo.io.IOStreamFactory;
import net.sf.midollo.net.cgitunnel.CGITunnelConstants;

import java.io.IOException;

public class CGITunnelConnection implements CGITunnelConstants {

	protected CGITunnelClient client;
	protected CGITunnelClientInputStream is;
	protected CGITunnelClientOutputStream os;

	public CGITunnelConnection(IOStreamFactory ioStreamFactory, String host, int port) throws IOException {
		this.client = new CGITunnelClient(ioStreamFactory, host, port);
	}

	public synchronized void connect() throws IOException {
		this.client.requestCmdOpen();
		this.os = new CGITunnelClientOutputStream(this.client);
		this.is = new CGITunnelClientInputStream(this.client);
	}

	public synchronized void disconnect() throws IOException {
		IOException error = tryRequestCmdClose(null);
		error = tryClose(error);
		if (error != null)
			throw error;
	}

	public CGITunnelClientInputStream getInputStream() throws IOException {
		return this.is;
	}

	public CGITunnelClientOutputStream getOutputStream() throws IOException {
		return this.os;
	}

	protected IOException tryRequestCmdClose(IOException error) {
		try {
			this.client.requestCmdClose();
		} catch (IOException e) {
			if (error == null)
				error = e;
		}
		return error;
	}

	protected IOException tryClose(IOException error) {
		try {
			this.client.close();
		} catch (IOException e) {
			if (error == null)
				error = e;
		}
		return error;
	}
}
